#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
Copyright (c) 2018 zzcat

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''

from __future__ import print_function
import math
import re
import sys
import os
import httplib
import md5
import urllib
import random
import json
import xlrd
import xlsxwriter


class Boot(object):
    # ============ 只改这里 ====================
    APPID = '你的APP ID'
    SECRET_KEY = '你的密钥'
    FILE_NAME = u'测试.xlsx'            # Excel文件名
    NEW_FILE_NAME = u'测试-结果.xlsx'   # 输出文件
    SHEET_NAME = u'测试'                # 页名
    START_CELL = 'C5'                  # 开始格子
    END_CELL = 'D19'                  # 结束格子
    SRC_LAN = 'jp'                      # 源语言
    DST_LAN = 'zh'                      # 目标语言
    # ============ ~只改这里 ====================


    @classmethod
    def row_name_2_real_name(cls, row_name):
        row_name = row_name.lower()
        result = 0
        for ch in row_name:
            result = result * 26 + (ord(ch) - 96)

        return int(result + 0.5)


    @classmethod
    def view_nam_2_real_name(cls, view_name):
        mat = re.match(r'([a-zA-Z]+)(\d+)', view_name)
        if not mat:
            cls.printu(u'格子号不对！')
            sys.exit(1)

        row = int(mat.group(2))
        column = cls.row_name_2_real_name(mat.group(1))

        return (row - 1, column - 1)


    @classmethod
    def get_cell_value(cls, work_sheet, row, column, tp):
        return tp(work_sheet.cell(row, column).value)


    @classmethod
    def printu(cls, u_text):
        if sys.platform == 'win32':
            print(u_text.encode('gbk'))
        else:
            print(u_text.encode('utf-8'))


    @classmethod
    def translate(cls, src_text):
        result = u'【翻译失败】'

        salt = random.randint(32768, 65536)
        sign = '%s%s%s%s' % (
            cls.APPID,
            src_text,
            salt,
            cls.SECRET_KEY
        )
        m1 = md5.new()
        m1.update(sign)
        sign = m1.hexdigest()

        translate_url = '/api/trans/vip/translate?appid=%s&q=%s&from=%s&to=%s&salt=%s&sign=%s' % (
            cls.APPID,
            src_text,
            cls.SRC_LAN,
            cls.DST_LAN,
            salt,
            sign
        )

        httpClient = None
        try:
            httpClient = httplib.HTTPConnection('api.fanyi.baidu.com')
            httpClient.request('GET', translate_url)

            response = httpClient.getresponse()
            ret = json.loads(response.read(), 'utf-8')
            if ret and ret['trans_result'] and len(ret['trans_result']) > 0:
                result = ret['trans_result'][0]['dst']
        except Exception, e:
            cls.printu(u"ERROR: 翻译%s失败：%s" % (src_text, e))
        finally:
            if httpClient:
                httpClient.close()

        return result


    @classmethod
    def boot(cls):
        excel_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), cls.FILE_NAME)
        work_book = xlrd.open_workbook(excel_file_path)
        work_sheet = work_book.sheet_by_name(cls.SHEET_NAME)
        start_row, start_column = cls.view_nam_2_real_name(cls.START_CELL)
        end_row, end_column = cls.view_nam_2_real_name(cls.END_CELL)
        collector = []

        for i in xrange(start_column, end_column + 1):
            for j in xrange(start_row, end_row + 1):
                src_text = cls.get_cell_value(work_sheet, j, i, unicode)
                cls.printu(u"翻译：%s" % src_text)
                src_text = src_text.encode('utf-8')
                dst_text = cls.translate(src_text)
                collector.append(dst_text)

        work_book = xlsxwriter.Workbook(os.path.join(os.path.dirname(os.path.abspath(__file__)), cls.NEW_FILE_NAME))
        work_sheet = work_book.add_worksheet()
        for idx, data in enumerate(collector):
            work_sheet.write(idx, 0, data)
        work_book.close()


if __name__ == '__main__':
    Boot.boot()
